using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Domain.Entities;
using UniversalAdmin.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace UniversalAdmin.Application.Services;

public class RolePermissionService : IRolePermissionService
{
    private readonly IRoleRepository _roleRepository;
    private readonly IPermissionRepository _permissionRepository;

    public RolePermissionService(IRoleRepository roleRepository, IPermissionRepository permissionRepository)
    {
        _roleRepository = roleRepository;
        _permissionRepository = permissionRepository;
    }

    // 为角色分配权限
    public async Task AssignPermissionsToRoleAsync(Guid roleId, List<Guid> permissionIds)
    {
        await _roleRepository.AssignPermissionsToRoleAsync(roleId, permissionIds);
    }

    // 清空角色权限
    public async Task ClearRolePermissionsAsync(Guid roleId)
    {
        await _roleRepository.ClearRolePermissionsAsync(roleId);
    }

    // 获取角色的权限列表
    public async Task<IEnumerable<PermissionDto>> GetRolePermissionsAsync(Guid roleId)
    {
        var permissions = await _roleRepository.GetPermissionsByRoleAsync(roleId);
        return permissions.Select(p => new PermissionDto(
            p.Id,
            p.Name,
            p.Description,
            p.Resource,
            p.Action,
            p.Type,
            p.SortOrder,
            p.IsEnabled
        ));
    }

    // 检查角色是否有指定权限
    public async Task<bool> HasPermissionAsync(Guid roleId, string resource, string action)
    {
        return await _roleRepository.HasPermissionAsync(roleId, resource, action);
    }

    // 获取用户的所有权限
    public async Task<IEnumerable<PermissionDto>> GetUserPermissionsAsync(Guid userId)
    {
        var permissions = await _roleRepository.GetUserPermissionsAsync(userId);
        return permissions.Select(p => new PermissionDto(
            p.Id,
            p.Name,
            p.Description,
            p.Resource,
            p.Action,
            p.Type,
            p.SortOrder,
            p.IsEnabled
        ));
    }

    // 检查用户是否有指定权限
    public async Task<bool> UserHasPermissionAsync(Guid userId, string resource, string action)
    {
        return await _roleRepository.UserHasPermissionAsync(userId, resource, action);
    }

    // 兼容旧版本的方法
    public Task AssignRolePermissionAsync(RolePermissionDto dto)
    {
        // 这个方法涉及菜单权限分配，需要创建IMenuRepository接口来支持
        // 暂时保留原有实现，后续可以进一步重构
        throw new NotImplementedException("此方法需要进一步重构以使用仓储接口");
    }

    public Task<List<Guid>> GetMenuIdsByRoleAsync(Guid roleId)
    {
        // 这个方法涉及菜单权限查询，需要创建IMenuRepository接口来支持
        // 暂时保留原有实现，后续可以进一步重构
        throw new NotImplementedException("此方法需要进一步重构以使用仓储接口");
    }
}